import React, { useState } from 'react';
import {
  Box,
  Paper,
  IconButton,
  Tooltip,
  Menu,
  MenuItem,
  ListItemIcon,
  ListItemText,
  Chip,
  Divider,
  Typography,
} from '@mui/material';
import {
  Mic,
  MicOff,
  Videocam,
  VideocamOff,
  CallEnd,
  Settings,
  VolumeUp,
  Headset,
  CameraAlt,
  KeyboardArrowDown,
} from '@mui/icons-material';
import { WebRTCConnectionState } from '@/types';
import { MediaDevices, CurrentDevices } from '@/hooks/useMediaDevices';

interface ControlPanelProps {
  isAudioEnabled: boolean;
  isVideoEnabled: boolean;
  connectionState: WebRTCConnectionState;
  devices: MediaDevices;
  currentDevices: CurrentDevices;
  onToggleAudio: () => void;
  onToggleVideo: () => void;
  onHangup: () => void;
  onDeviceSwitch: (deviceType: 'audioinput' | 'videoinput' | 'audiooutput', deviceId: string) => void;
}

const ControlPanel: React.FC<ControlPanelProps> = ({
  isAudioEnabled,
  isVideoEnabled,
  connectionState,
  devices,
  currentDevices,
  onToggleAudio,
  onToggleVideo,
  onHangup,
  onDeviceSwitch,
}) => {
  const [settingsAnchor, setSettingsAnchor] = useState<null | HTMLElement>(null);
  const [audioInputAnchor, setAudioInputAnchor] = useState<null | HTMLElement>(null);
  const [videoInputAnchor, setVideoInputAnchor] = useState<null | HTMLElement>(null);
  const [audioOutputAnchor, setAudioOutputAnchor] = useState<null | HTMLElement>(null);

  const handleSettingsClick = (event: React.MouseEvent<HTMLElement>) => {
    setSettingsAnchor(event.currentTarget);
  };

  const handleSettingsClose = () => {
    setSettingsAnchor(null);
  };

  const handleAudioInputClick = (event: React.MouseEvent<HTMLElement>) => {
    setAudioInputAnchor(event.currentTarget);
  };

  const handleAudioInputClose = () => {
    setAudioInputAnchor(null);
  };

  const handleVideoInputClick = (event: React.MouseEvent<HTMLElement>) => {
    setVideoInputAnchor(event.currentTarget);
  };

  const handleVideoInputClose = () => {
    setVideoInputAnchor(null);
  };

  const handleAudioOutputClick = (event: React.MouseEvent<HTMLElement>) => {
    setAudioOutputAnchor(event.currentTarget);
  };

  const handleAudioOutputClose = () => {
    setAudioOutputAnchor(null);
  };

  const handleDeviceSelect = (
    deviceType: 'audioinput' | 'videoinput' | 'audiooutput',
    deviceId: string
  ) => {
    onDeviceSwitch(deviceType, deviceId);
    // 关闭所有菜单
    setAudioInputAnchor(null);
    setVideoInputAnchor(null);
    setAudioOutputAnchor(null);
    setSettingsAnchor(null);
  };

  const getConnectionStatusColor = () => {
    switch (connectionState) {
      case 'connected':
        return 'success';
      case 'connecting':
        return 'warning';
      case 'disconnected':
      case 'failed':
        return 'error';
      default:
        return 'default';
    }
  };

  const getConnectionStatusText = () => {
    switch (connectionState) {
      case 'connected':
        return '已连接';
      case 'connecting':
        return '连接中';
      case 'disconnected':
        return '已断开';
      case 'failed':
        return '连接失败';
      default:
        return '未知状态';
    }
  };

  return (
    <Paper
      elevation={3}
      sx={{
        mt: 2,
        p: 2,
        borderRadius: 2,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
      }}
    >
      {/* 连接状态 */}
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
        <Chip
          label={getConnectionStatusText()}
          color={getConnectionStatusColor()}
          size="small"
          variant="outlined"
        />
      </Box>

      {/* 主要控制按钮 */}
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
        {/* 麦克风控制 */}
        <Tooltip title={isAudioEnabled ? '静音' : '取消静音'}>
          <IconButton
            onClick={onToggleAudio}
            size="large"
            sx={{
              backgroundColor: isAudioEnabled ? 'primary.main' : 'error.main',
              color: 'white',
              '&:hover': {
                backgroundColor: isAudioEnabled ? 'primary.dark' : 'error.dark',
              },
            }}
          >
            {isAudioEnabled ? <Mic /> : <MicOff />}
          </IconButton>
        </Tooltip>

        {/* 摄像头控制 */}
        <Tooltip title={isVideoEnabled ? '关闭摄像头' : '开启摄像头'}>
          <IconButton
            onClick={onToggleVideo}
            size="large"
            sx={{
              backgroundColor: isVideoEnabled ? 'primary.main' : 'error.main',
              color: 'white',
              '&:hover': {
                backgroundColor: isVideoEnabled ? 'primary.dark' : 'error.dark',
              },
            }}
          >
            {isVideoEnabled ? <Videocam /> : <VideocamOff />}
          </IconButton>
        </Tooltip>

        {/* 挂断 */}
        <Tooltip title="挂断">
          <IconButton
            onClick={onHangup}
            size="large"
            sx={{
              backgroundColor: 'error.main',
              color: 'white',
              '&:hover': {
                backgroundColor: 'error.dark',
              },
            }}
          >
            <CallEnd />
          </IconButton>
        </Tooltip>
      </Box>

      {/* 设备设置 */}
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
        <Tooltip title="设备设置">
          <IconButton
            onClick={handleSettingsClick}
            sx={{
              color: 'text.secondary',
              '&:hover': {
                backgroundColor: 'action.hover',
              },
            }}
          >
            <Settings />
          </IconButton>
        </Tooltip>
      </Box>

      {/* 设备设置菜单 */}
      <Menu
        anchorEl={settingsAnchor}
        open={Boolean(settingsAnchor)}
        onClose={handleSettingsClose}
        PaperProps={{
          sx: { minWidth: 200 },
        }}
      >
        <MenuItem onClick={handleAudioInputClick}>
          <ListItemIcon>
            <Mic />
          </ListItemIcon>
          <ListItemText primary="麦克风" />
          <KeyboardArrowDown />
        </MenuItem>
        
        <MenuItem onClick={handleVideoInputClick}>
          <ListItemIcon>
            <CameraAlt />
          </ListItemIcon>
          <ListItemText primary="摄像头" />
          <KeyboardArrowDown />
        </MenuItem>
        
        <MenuItem onClick={handleAudioOutputClick}>
          <ListItemIcon>
            <VolumeUp />
          </ListItemIcon>
          <ListItemText primary="扬声器" />
          <KeyboardArrowDown />
        </MenuItem>
      </Menu>

      {/* 麦克风选择菜单 */}
      <Menu
        anchorEl={audioInputAnchor}
        open={Boolean(audioInputAnchor)}
        onClose={handleAudioInputClose}
        PaperProps={{
          sx: { minWidth: 250 },
        }}
      >
        <Typography variant="subtitle2" sx={{ px: 2, py: 1, fontWeight: 600 }}>
          选择麦克风
        </Typography>
        <Divider />
        {devices.audioInput.map((device) => (
          <MenuItem
            key={device.deviceId}
            onClick={() => handleDeviceSelect('audioinput', device.deviceId)}
            selected={device.deviceId === currentDevices.audioInput?.deviceId}
          >
            <ListItemIcon>
              <Mic />
            </ListItemIcon>
            <ListItemText
              primary={device.label || `麦克风 ${device.deviceId.slice(0, 8)}`}
              secondary={device.deviceId === currentDevices.audioInput?.deviceId ? '当前使用' : ''}
            />
          </MenuItem>
        ))}
        {devices.audioInput.length === 0 && (
          <MenuItem disabled>
            <ListItemText primary="未找到麦克风设备" />
          </MenuItem>
        )}
      </Menu>

      {/* 摄像头选择菜单 */}
      <Menu
        anchorEl={videoInputAnchor}
        open={Boolean(videoInputAnchor)}
        onClose={handleVideoInputClose}
        PaperProps={{
          sx: { minWidth: 250 },
        }}
      >
        <Typography variant="subtitle2" sx={{ px: 2, py: 1, fontWeight: 600 }}>
          选择摄像头
        </Typography>
        <Divider />
        {devices.videoInput.map((device) => (
          <MenuItem
            key={device.deviceId}
            onClick={() => handleDeviceSelect('videoinput', device.deviceId)}
            selected={device.deviceId === currentDevices.videoInput?.deviceId}
          >
            <ListItemIcon>
              <CameraAlt />
            </ListItemIcon>
            <ListItemText
              primary={device.label || `摄像头 ${device.deviceId.slice(0, 8)}`}
              secondary={device.deviceId === currentDevices.videoInput?.deviceId ? '当前使用' : ''}
            />
          </MenuItem>
        ))}
        {devices.videoInput.length === 0 && (
          <MenuItem disabled>
            <ListItemText primary="未找到摄像头设备" />
          </MenuItem>
        )}
      </Menu>

      {/* 扬声器选择菜单 */}
      <Menu
        anchorEl={audioOutputAnchor}
        open={Boolean(audioOutputAnchor)}
        onClose={handleAudioOutputClose}
        PaperProps={{
          sx: { minWidth: 250 },
        }}
      >
        <Typography variant="subtitle2" sx={{ px: 2, py: 1, fontWeight: 600 }}>
          选择扬声器
        </Typography>
        <Divider />
        {devices.audioOutput.map((device) => (
          <MenuItem
            key={device.deviceId}
            onClick={() => handleDeviceSelect('audiooutput', device.deviceId)}
            selected={device.deviceId === currentDevices.audioOutput?.deviceId}
          >
            <ListItemIcon>
              <VolumeUp />
            </ListItemIcon>
            <ListItemText
              primary={device.label || `扬声器 ${device.deviceId.slice(0, 8)}`}
              secondary={device.deviceId === currentDevices.audioOutput?.deviceId ? '当前使用' : ''}
            />
          </MenuItem>
        ))}
        {devices.audioOutput.length === 0 && (
          <MenuItem disabled>
            <ListItemText primary="未找到扬声器设备" />
          </MenuItem>
        )}
      </Menu>
    </Paper>
  );
};

export default ControlPanel;